$(document).ready(function() {

    const $accountInput = $('#account');
    const $nicknameInput = $('#username');
    const $passwordInput = $('#password');
    const $repeatPasswordInput = $('#repeat-password');
    const $form = $('#myForm');
    const $submitButton = $('#bt');
    const $avatar =  $('#selected-avatar-path');

    $form.submit(function(event) {
        event.preventDefault();
    });

    $submitButton.click(function() {
        const account = $accountInput.val();
        let nickname = $nicknameInput.val();
        const password = $passwordInput.val();
        const repeatPassword = $repeatPasswordInput.val();
        const avatar = decodeURIComponent($avatar.val());

        if (account === "" || password === "" || repeatPassword === "") {
            showInfo('账号和密码不能为空！');
            return;
        }

        if (nickname === "") {
            const confirmNicknameUse = confirm("未设置昵称将使用账号名作为默认昵称，是否继续？");
            if (confirmNicknameUse) {
                nickname = account;
            } else {
                return;
            }
        }

        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;

        if (!passwordRegex.test(password)) {
            showInfo('新密码必须至少包含8个字符，且包含字母和数字。');
            return;
        }

        if (password !== repeatPassword) {
            showInfo('密码和重复密码不一致！');
            return;
        }

        $.ajax({
            // 请求
            url:"/register",
            method:"get",
            // 响应
            dataType:"text",
            data: {account: account, nickName: nickname, password: password, avatar: avatar},
            success: function(data) {
                if (data === "exits"){
                    showInfo('用户已存在！');
                } else if (data === "success"){
                    showInfo('注册成功！');
                    window.location.href = 'login.html';
                } else if (data === "fail"){
                    showInfo('注册失败！')
                }
            }
        })
    });
});

const avatars = [
    './images/avatar/image1.jpg',
    './images/avatar/image2.jpg',
    './images/avatar/image3.JPG',
];

const avatarSelection = document.getElementById('avatar-selection');
const selectedAvatar = document.getElementById('selected-avatar');

avatars.forEach((avatar, index) => {
    const img = document.createElement('img');
    img.src = avatar;
    img.alt = `Avatar ${index + 1}`;
    img.onclick = () => selectAvatar(avatar);
    avatarSelection.appendChild(img);
});

function toggleAvatarSelection() {
    avatarSelection.style.display = avatarSelection.style.display === 'none' ? 'block' : 'none';
}

function selectAvatar(avatar) {
    selectedAvatar.src = avatar;
    avatarSelection.style.display = 'none';
    // 这里可以将头像路径存储在一个隐藏的输入字段中，提交表单时发送到服务器
    document.getElementById('selected-avatar-path').value = avatar;
}
